#include <iostream>
#include <boost/bind.hpp>

#include "SimpleTcpServer.h"
#include "SimpleTcpConnection.h"

#include <tbb/tick_count.h>


using namespace boost::asio;
using namespace tbb;
using namespace std;


SimpleTcpServer::SimpleTcpServer(unsigned short port /* = 80 */)
	: _acceptor(_ioService)
{
	ip::tcp::endpoint endpoint(ip::tcp::v4(), port);

	_acceptor.open(endpoint.protocol());
	_acceptor.set_option(ip::tcp::acceptor::reuse_address(true));
	_acceptor.bind(endpoint);
	_acceptor.listen();
}

void SimpleTcpServer::Run(bool showStat /* = false */)
{
	tbb_thread *thread = NULL;
	size_t accepts = 0;
	size_t skips = 0;
	tick_count startTime = tick_count::now();

	while (true)
	{
		SimpleTcpConnection *connection = new SimpleTcpConnection(_ioService);
		_acceptor.accept(connection->getSocket());

		delete thread;
		thread = new tbb_thread(boost::bind(&SimpleTcpConnection::StartParsing, connection));

		if (showStat)
		{
			++accepts;

			tick_count stopTime = tick_count::now();

			if ((stopTime - startTime).seconds() < 1)
			{	// Skip too small iterations not to slow down the server with I/O
				++skips;
			}
			else
			{
				cout << fixed << "Skips: " << skips << ", accepted: " << accepts << '\n'
					 << "Time: " << (stopTime - startTime).seconds() * 1000 << ", acc/sec: " << accepts / (stopTime - startTime).seconds() << endl;

				accepts = skips = 0;
				startTime = stopTime;
			}
		}
	}

	delete thread;
}